package cn.ddm.hrm.services.iml;

import cn.ddm.hrm.exception.ErrorCode;
import cn.ddm.hrm.exception.ValidUtils;
import cn.ddm.hrm.services.IImgVerifyCodeService;
import cn.ddm.hrm.util.AjaxResult;
import cn.ddm.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ImgVerifyCodeServiceImpl implements IImgVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult getCodeByKey(String imageCodeKey) {
        // 校验
        ValidUtils.assertNotNull(imageCodeKey, ErrorCode.CODE_400_USER_IMG_CODE);
        // 生成随机验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);

        // 将验证码写入图片
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            VerifyCodeUtils.outputImage(150, 50, data, code);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将图片转换为base64
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Encode = encoder.encode(data.toByteArray());
        // 保存验证码Redis中
        redisTemplate.opsForValue().set(imageCodeKey, code, 3, TimeUnit.MINUTES);
        // 返回参数
        return AjaxResult.me().setResultObj(base64Encode);
    }

    @Override
    public AjaxResult verifyImgCode(Map<String, String> params) {
        // 获取参数
        String mobile = params.get("mobile");
        String imageCode = params.get("imageCode");
        String imageCodeKey = params.get("imageCodeKey");
        // 判断图片验证码是否过期,是否正确
        // 查询Redis
        String code = (String) redisTemplate.opsForValue().get(imageCodeKey);
        ValidUtils.assertNotNull(code, ErrorCode.CODE_400_USER_CODE_TIME);
        // 判断两次验证码是否一致
        ValidUtils.assertEqual(code, imageCode, ErrorCode.CODE_400_CODE_EQUAL);
        return new AjaxResult();
    }
}
